package com.osfw.dbadminer.controller.database;

import com.osfw.framework.annotation.Log;
import com.osfw.framework.exception.ServiceException;
import com.osfw.framework.enums.BusinessType;
import com.osfw.dbadminer.service.database.IDbaDataFunctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


/**
 * 数据库操作
 */
@Controller
@RequestMapping("/osfw/dbadminer/database/func")
public class DbaDatabaseFuncController {
    private String prefix = "osfw/dbadminer/database";

    @Autowired
    private IDbaDataFunctionService dataFunctionService;


    @GetMapping("/{connectId}/{connectName}/{databaseName}")
    public String allFunctions(@PathVariable Long connectId, @PathVariable String connectName, @PathVariable String databaseName, ModelMap mmap) {
        mmap.put("connectId", connectId);
        mmap.put("connectName", connectName);
        mmap.put("databaseName", databaseName);
        List<String> funcs = null;
        Integer maxRem = 0;
        try {
            funcs = dataFunctionService.getAllFunctions(connectId, databaseName);
            maxRem = funcs.stream().max(Comparator.comparingInt(x -> x.length())).orElse("").length();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        mmap.put("funcs", funcs);
        mmap.put("maxrem", maxRem + 15);
        return prefix + "/func";
    }

    @Log(title = "查询数据库存储过程", businessType = BusinessType.GRANT)
    @GetMapping("/list/{connectId}/{database}")
    @ResponseBody
    public List<String> list(@PathVariable("connectId") Long connectId, @PathVariable("database") String database) {
        try {
            List<String> funcs = dataFunctionService.getAllFunctions(connectId, database);
            return funcs;
        } catch (SQLException e) {
            e.printStackTrace();
            ServiceException.throw500("查询异常");
        }
        return new ArrayList<>();
    }

}
